package com.zhq.apputil.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;

import com.zhq.apputil.R;
import com.zhq.apputil.utils.ScreenUtils;
import com.zhq.apputil.widget.config.TabBarItemBean;

import androidx.viewpager.widget.ViewPager;


/**
 * @Author: Zhq
 * @Date: 2019/2/13 15:55
 * @Description: tabBar自定义指示器
 */
public class TabBarIndicatorLayout extends HorizontalScrollView implements View.OnClickListener, ViewPager.OnPageChangeListener {
    private int indicatorColor;//指示器的颜色
    private int tabSelectNormalColor;//tab正常的颜色
    private int tabSelectPressedColor;//tab选中的颜色
    private int marginPadding;
    private int mTabVisibleCount = 0;
    private TabBarItemBean barIndicator;
    private LinearLayout mTabsContainer;
    private int mCurrentTab = 0;
    private float selectFontSize, unSelectFontSize;
    private Paint mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);//绘画笔
    private int underlinePadding = 0;//指示器线条padding的大小
    private int currentPosition = 0;//当前选中的位置
    private float currentPositionOffset = 0;//当前位置的位移
    private int lastScrollX = 0;//最后一次X轴的距离
    private Paint underlinePaint;//指示器线条画笔
    private int indicatorHeight = 2;//指示器的高度
    private boolean isRoundUnderIndicator;//是否显示圆柱形指示器
    private ITabBarOnListener onTabBarOnListener;
    private boolean isScrolled;
    private boolean isTitleBold;//是否加粗
    private int screeWidth;
    private ViewPager mViewPager;
    private CharSequence[] mLabels;

    public TabBarIndicatorLayout(Context context) {
        super(context);
    }

    public TabBarIndicatorLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    /***
     * 初始化
     * @param context
     * @param attrs
     */
    public void init(Context context, AttributeSet attrs) {
        setFillViewport(true);//设置滚动视图是否可以伸缩其内容以填充视口
        setClipChildren(false);
        setClipToPadding(false);
        setHorizontalScrollBarEnabled(false);//水平方向的水平滚动条是否显示
        marginPadding = ScreenUtils.dpToPx(context.getResources(), 15);
        screeWidth = ScreenUtils.getScreenWidth(context);
        mTabsContainer = new LinearLayout(context);
        mTabsContainer.setOrientation(LinearLayout.HORIZONTAL);
        mTabsContainer.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
        addView(mTabsContainer);

        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.TabBarIndicatorLayout);
        tabSelectNormalColor = typedArray.getColor(R.styleable.TabBarIndicatorLayout_tab_color_normal, Color.parseColor("#242D34"));
        tabSelectPressedColor = typedArray.getColor(R.styleable.TabBarIndicatorLayout_tab_color_pressed, Color.parseColor("#ff2a2a"));
        indicatorColor = typedArray.getColor(R.styleable.TabBarIndicatorLayout_indicator_color, Color.parseColor("#ff2a2a"));
        mTabVisibleCount = typedArray.getColor(R.styleable.TabBarIndicatorLayout_tab_count, 0);
        selectFontSize = typedArray.getDimension(R.styleable.TabBarIndicatorLayout_tab_text_select_font_size, 15f);
        unSelectFontSize = typedArray.getDimension(R.styleable.TabBarIndicatorLayout_tab_text_unselect_font_size, 13f);
        // 读取布局中，各个tab使用的文字
        if (typedArray.hasValue(R.styleable.TabBarIndicatorLayout_tab_text_labels)) {
            mLabels = typedArray.getTextArray(R.styleable.TabBarIndicatorLayout_tab_text_labels);
        }
        typedArray.recycle();
        underlinePaint = new Paint();
        underlinePaint.setColor(indicatorColor);
        underlinePaint.setStyle(Paint.Style.FILL);
        underlinePaint.setAntiAlias(true);
        initLayout();
    }


    /**
     * 初始化布局
     **/
    public void initLayout() {
        underlinePaint.setColor(indicatorColor);
        for (int i = 0; i < mTabVisibleCount; i++) {
            IconTextView iconTextView = new IconTextView(getContext());
            iconTextView.setTag(i);
            iconTextView.setGravity(Gravity.CENTER);
            if (isTitleBold) {
                iconTextView.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
                iconTextView.setFontBold(true);
            } else {
                iconTextView.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
                iconTextView.setFontBold(false);
            }
            if (mCurrentTab == i) {
                iconTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, selectFontSize);
                iconTextView.setTextColor(tabSelectPressedColor);
            } else {
                iconTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, unSelectFontSize);
                iconTextView.setTextColor(tabSelectNormalColor);
            }
            if (isScrolled) {
                iconTextView.setPadding(marginPadding, 0, marginPadding, 0);
            }
            if (mLabels != null && mTabVisibleCount == mLabels.length) {
                iconTextView.setText(mLabels[i]);
            }
            iconTextView.setOnClickListener(this);
            iconTextView.setLayoutParams(getLinearLayoutParams());
            mTabsContainer.addView(iconTextView);
        }
        if (mLabels != null && mLabels.length > 0) {
            mTextPaint.setTextSize(((IconTextView) getItem(mCurrentTab)).getTextSize());
        }
        if (mViewPager != null) {
            mViewPager.removeOnPageChangeListener(this);
            mViewPager.addOnPageChangeListener(this);
        }

    }


    private LinearLayout.LayoutParams getLinearLayoutParams() {
        return isScrolled ?
                new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT)
                : new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1.0f);
    }


    /**
     * @param position :所选中的位置
     */
    public void selectTabBarItem(int position) {
        if (mCurrentTab < mTabVisibleCount) {
            IconTextView selectTabView = (IconTextView) getItem(position);
            IconTextView unSelectTabView = (IconTextView) getItem(mCurrentTab);
            unSelectTabView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, unSelectFontSize);
            unSelectTabView.setTextColor(tabSelectNormalColor);
            selectTabView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, selectFontSize);
            selectTabView.setTextColor(tabSelectPressedColor);
            this.mCurrentTab = position;
        }
        if (onTabBarOnListener != null && barIndicator != null) {
            barIndicator.setPosition(position);
            onTabBarOnListener.onTabBarSelect(barIndicator);
        }
    }


    /**
     * @param barIndicator ：布局所需要的参数
     **/
    public TabBarIndicatorLayout setTabBarIndicator(TabBarItemBean barIndicator) {
        this.barIndicator = barIndicator;
        this.mTabVisibleCount = barIndicator.getTitle() != null ? barIndicator.getTitle().length : 0;
        this.tabSelectNormalColor = barIndicator.getFontNormalColor();
        this.tabSelectPressedColor = barIndicator.getFontPressedColor();
        this.mLabels = barIndicator.getTitle();
        this.indicatorColor = barIndicator.getIndicatorColor();
        this.indicatorHeight = barIndicator.getIndicatorHeight();
        this.mCurrentTab = barIndicator.getPosition();
        this.mViewPager = barIndicator.getViewPager();
        this.isScrolled = barIndicator.isScrolled();
        this.isTitleBold = barIndicator.isTitleBold();
        this.isRoundUnderIndicator = barIndicator.isRoundUnderIndicator();
        this.selectFontSize = barIndicator.getSelectFontSize();
        this.unSelectFontSize = barIndicator.getUnSelectFontSize();
        return this;
    }

    /**
     * @param mLabels ：修改tabTar
     **/
    public TabBarIndicatorLayout updateTabBarTextView(String[] mLabels) {
        this.mLabels = mLabels;
        this.mTabVisibleCount = mLabels.length;
        if (barIndicator != null) {
            barIndicator.setTitle(mLabels);
        }
        return this;
    }

    /***
     * 获取item的选择类型
     * @return
     */
    public Integer getItemType() {
        int position = getCurrentPosition();
        return barIndicator.getBarType()[position];
    }

    /**
     * 获取选中的位置
     */
    public int getCurrentPosition() {
        return mCurrentTab;
    }

    /**
     * 显示布局
     */
    public void show() {
        mTabsContainer.removeAllViews();//清空所有定义的view
        initLayout();
    }


    @Override
    public void onClick(View v) {
        int position = (int) v.getTag();
        if (mViewPager != null) {
            mViewPager.setCurrentItem(position);
        } else {
            currentPosition = position;
            invalidate();
            selectTabBarItem(position);
            scrollToChild(position, 0);
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        drawUnderline(canvas);
    }

    /****
     * 获取当前位置的View
     * @param position
     * @return
     */
    private View getItem(int position) {
        return mTabsContainer.getChildAt(position);
    }


    /****
     * 画下面的线
     * @param canvas
     */
    private void drawUnderline(Canvas canvas) {
        View currentTab = getItem(currentPosition);
        if (currentTab != null) {
            //String text = mLabels[mCurrentTab].toString();//拿到文本
            //int textWidth = (int) mTextPaint.measureText(text);//测量一下宽度
            //int mViewWidth = mTabsContainer.getWidth();
            //int mViewHeight = mTabsContainer.getHeight();
            // int perWidth = mViewWidth / mTabVisibleCount;//每个Tab的平均宽度


//            int contentWidth = (perWidth - textWidth) / 4;//获取左右边距距离
//            LogUtil.e("平均的宽度：" + perWidth + "字体宽度：" + textWidth + " contentWidth:" + contentWidth);
//            rectF.set(
//                    perWidth * (currentPosition + currentPositionOffset) + perWidth / 2 - textWidth,
//                    mViewHeight - indicatorHeight,
//                    perWidth * (currentPosition + currentPositionOffset) + perWidth / 2 + textWidth / 2,
//                    mViewHeight);
//            canvas.drawRect(rectF, underlinePaint);

            // perWidth / 2 - textWidth / 2
            //perWidth / 2 + textWidth / 2
            underlinePadding = getLinePadding();
            float lineLeft = currentTab.getLeft() + underlinePadding;
            float lineRight = currentTab.getRight() - underlinePadding;
            // if there is an offset, start interpolating left and right coordinates between current and next tab
            if (currentPositionOffset > 0f && currentPosition < mTabVisibleCount - 1) {
                View nextTab = getItem(currentPosition + 1);
                float nextTabLeft = nextTab.getLeft() + underlinePadding;
                float nextTabRight = nextTab.getRight() - underlinePadding;
                lineLeft = (currentPositionOffset * nextTabLeft + (1f - currentPositionOffset) * lineLeft);
                lineRight = (currentPositionOffset * nextTabRight + (1f - currentPositionOffset) * lineRight);
            }
            if (isRoundUnderIndicator) {
                RectF oval3 = new RectF(lineLeft, getHeight() - indicatorHeight, lineRight, getHeight());// 设置个新的长方形
                canvas.drawRoundRect(oval3, 20, 15, underlinePaint);//第二个参数是x半径，第三个参数是y半径
            } else {
                canvas.drawRect(lineLeft, getHeight() - indicatorHeight, lineRight, getHeight(), underlinePaint);
            }

        }


    }

    /***
     * 判断scrolled：true 横向滑动排列 false 权重排列
     * 算出指示器的宽度，再通过获取文本内容的宽度算出指示器的padding距离
     * @return
     */
    public int getLinePadding() {
        if (mLabels != null && mLabels.length > 0) {
            int indicatorContentWidth = isScrolled ? getItem(currentPosition).getWidth() : screeWidth / mTabVisibleCount;
            float textWidth = mTextPaint.measureText(mLabels[mCurrentTab].toString());
            int margin = (int) ((indicatorContentWidth - textWidth) / 2);
            return margin;
        }
        return 0;
    }


    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        currentPosition = position;
        currentPositionOffset = positionOffset;
        invalidate();
    }


    @Override
    public void onPageSelected(int position) {
        selectTabBarItem(position);
    }


    @Override
    public void onPageScrollStateChanged(int state) {
        if (state == ViewPager.SCROLL_STATE_IDLE && mViewPager != null) {
            scrollToChild(mViewPager.getCurrentItem(), 0);
        }
    }


    @Override
    protected Parcelable onSaveInstanceState() {
        Parcelable superState = super.onSaveInstanceState();
        SaveState saveState = new SaveState(superState);
        saveState.position = currentPosition;
        return saveState;

    }

    @Override
    protected void onRestoreInstanceState(Parcelable state) {
        SaveState savedState = (SaveState) state;
        super.onRestoreInstanceState(savedState.getSuperState());
        currentPosition = savedState.position;
        selectTabBarItem(currentPosition);
    }

    static class SaveState extends BaseSavedState {
        int position;

        @Override
        public int describeContents() {
            return 0;
        }


        @Override
        public void writeToParcel(Parcel dest, int flags) {
            super.writeToParcel(dest, flags);
            dest.writeInt(this.position);
        }


        public SaveState(Parcelable superState) {
            super(superState);
        }


        protected SaveState(Parcel in) {
            super(in);
            this.position = in.readInt();

        }


        public static final Creator<SaveState> CREATOR = new Creator<SaveState>() {
            @Override
            public SaveState createFromParcel(Parcel source) {
                return new SaveState(source);
            }


            @Override
            public SaveState[] newArray(int size) {
                return new SaveState[size];
            }

        };

    }

    /***
     * 滑动到某个子view
     * @param position
     * @param offset
     */
    private void scrollToChild(int position, int offset) {
        if (mTabVisibleCount == 0) {
            return;
        }
        if (getItem(position) != null) {
            int newScrollX = getItem(position).getLeft() + offset;
            if (newScrollX != lastScrollX) {
                lastScrollX = newScrollX;
                scrollTo(newScrollX, 0);
            }
        }
    }

    /**
     * @param onTabBarOnListener:监听器
     **/
    public void setOnTabBarOnListener(ITabBarOnListener onTabBarOnListener) {
        this.onTabBarOnListener = onTabBarOnListener;
    }


    /****
     * 指示器滑动监听器
     */
    public interface ITabBarOnListener {
        void onTabBarSelect(TabBarItemBean barItemBean);
    }

}
